//
//  LoginWindow.m
//  weibo3
//
//  Created by Tian Wu on 11-4-12.
//  Copyright 2011年 nfsysu. All rights reserved.
//

#import "LoginWindow.h"

extern RootViewController * rootView;

@implementation LoginWindow


- (NSString *)windowNibName
{
	return @"OAuthLogin";
}



- (NSString *)edit:(NSString *)startingValues from:(RootViewController *)sender
{
	NSWindow *selfwindow = [self window];
    

    
	cancelled = NO;
    
    [self loadWindow];
    

    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"autologin"]) {
        [Autologin setState:NSOnState];
    }
    else{
        [Autologin setState:NSOffState];
    }
    
    NSURL *url = [NSURL URLWithString:startingValues];

    [[loginView mainFrame] loadRequest:[NSURLRequest requestWithURL:url]];
    /*
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"username"]!= nil) {
        [UserName setTitleWithMnemonic:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]];
    }
     */
	[NSApp beginSheet:selfwindow modalForWindow:[sender window] modalDelegate:nil didEndSelector:nil contextInfo:nil];
	[NSApp runModalForWindow:selfwindow];
	// sheet is up here...
    
	[NSApp endSheet:selfwindow];
	[selfwindow orderOut:self];
    
    return pinCode;
}
/*
- (IBAction)done:(id)sender
{
    cancelled = NO;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    [logining startAnimation:nil];
    
    NSString *usernamebak = [defaults stringForKey:@"username"];
    NSString *passwordbak = [defaults stringForKey:@"password"];

    
    [defaults setObject:[UserName stringValue] forKey:@"username"];
    [defaults setObject:[PassWord stringValue] forKey:@"password"];
    
    
    User *user = [_rootViewController verifyUser];
    
    if ([user name] == nil) {
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]){
            [defaults setObject:usernamebak forKey:@"username"];
            [defaults setObject:passwordbak forKey:@"password"];
        }
        else{
        [defaults setObject:@"" forKey:@"username"];
        [defaults setObject:@"" forKey:@"password"];
        }
        NSAlert *alert = [NSAlert alertWithMessageText:@"发生了一点错误" defaultButton:@"重新输入" alternateButton:nil otherButton:nil informativeTextWithFormat:@"登录失败！请检查：1.帐号密码是否正确；2.是否已连接到互联网。"];
        [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:nil contextInfo:NULL];
        [logining stopAnimation:nil];
        
    }
    else{
        [_rootViewController loginInit];
        
        [logining stopAnimation:nil];
        
        
        [NSApp stopModal];
    }
	
    
	
}
 */


- (NSString *) locateAuthPinInWebView: (WebView *) webView {
	//NSString			*js = @"var r = new RegExp('^\\d{6}$'); var d = r.exec(document.body.innerHTML); if (d.length > 0) d = d[0]; d.replace(/^\\s*/, '').replace(/\\s*$/, ''); d;";
	NSString			*pin;
	
    //NSLog(@"pin is %@",pin);
    
    //if (pin.length > 0) return pin;
	
	NSString			*html = [loginView stringByEvaluatingJavaScriptFromString: @"document.body.innerText"];
	//NSLog(@"html:%@", [loginView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"]);
	
	if (html.length == 0) return nil;
	
	const char			*rawHTML = (const char *) [html UTF8String];
	int					length = (int)strlen(rawHTML), chunkLength = 0;
	
	for (int i = 0; i < length; i++) {
		if (rawHTML[i] < '0' || rawHTML[i] > '9') {
			if (chunkLength == 6) {
				char				*buffer = (char *) malloc(chunkLength + 1);
				
				memmove(buffer, &rawHTML[i - chunkLength], chunkLength);
				buffer[chunkLength] = 0;
				
				pin = [NSString stringWithUTF8String: buffer];
				free(buffer);
                NSLog(@"pin is %@",pin);
				return pin;
			}
			chunkLength = 0;
		} else
			chunkLength++;
	}
	
	return nil;
}

- (void) getPin{
    
    NSString *pin = [self locateAuthPinInWebView:loginView];
    
    if (pin) {
        pinCode = pin;
        [NSApp stopModal];
    }
    
    
    
}

- (IBAction)cancel:(id)sender
{
    cancelled = YES;
	[NSApp stopModal];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
        [NSApp endSheet:[self window]];
        [[NSApplication sharedApplication] terminate:self];
        
    }
    
}

- (BOOL)wasCancelled
{
	return cancelled;
}


- (IBAction) autoLoginDidChange:(id)sender{
    
    if([Autologin state] == NSOnState){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"autologin"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"autologin"];
    }
    
}






- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(getPin) 
                   name:WebViewProgressFinishedNotification
                 object:nil];
    }
    
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

@end
